<template>
  <div class="register">

    <div class="container">
      <div class="w">
        <div class="register-form">
          <el-link type="primary" class="toLogin" @click="goPage('Login')">已有账号，点击登录</el-link>
          <h1 class="title">注册账号</h1>
          <el-form :model="userInfo" :rules="rules" ref="ruleForm" label-width="90px" class="demo-ruleForm">
            <el-form-item label="昵称:" prop="userName">
              <el-input v-model="userInfo.userName"></el-input>
              <div class="tip">
                <el-tooltip class="item" effect="dark" content="长度在 2 到 5 个字符" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="手机号:" prop="phoneNumber">
              <el-input v-model="userInfo.phoneNumber"></el-input>
              <div class="tip">
                <el-tooltip class="item" effect="dark" content="请输入手机号" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input v-model="userInfo.password" show-password></el-input>
              <div class="tip">
                <el-tooltip class="item" effect="dark" content="长度 5 到 10 位字母数字下划线组合" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="确认密码:" prop="checkPass">
              <el-input v-model="userInfo.checkPass" show-password></el-input>
              <div class="tip">
                <el-tooltip class="item" effect="dark" content="长度 5 到 10 位字母数字下划线组合" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
              <el-input v-model="userInfo.email"></el-input>
              <div class="tip">
                <el-tooltip class="item" effect="dark" content="以字母为首 3 到 10 个字母和数字组合" placement="right">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item label="验证码:" prop="validcode">
              <el-input v-model="userInfo.validcode" class="validcode"></el-input>
              <el-button type="primary" @click="sendCode" :disabled="isSend">{{text}}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">立即注册</el-button>
              <el-button type="primary" @click="resetForm('ruleForm')">重置</el-button>

            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import "@/assets/less/register.less";
export default {
  name: "Register",


  data() {

    return {
      // 用户注册信息
      userInfo: {
        userName: "",
        email: "",
        password: "",
        checkPass: "",
        phoneNumber: "",
        validcode: "",
      },
      // 验证规则
      rules: {
        userName: [{ required: true, validator: this.validateUserName, trigger: "blur" }],
        email: [
          { required: true, validator: this.validateEmail, trigger: "blur" },
        ],
        password: [
          { required: true, validator: this.validatePass, trigger: "blur" },
        ],
        checkPass: [
          { required: true, validator: this.validatePass2, trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, validator: this.validatePhone, trigger: "blur" },
        ],
        validcode: [{ required: true, validator: this.validateCode, trigger: "blur" }],
      },
      // 验证码id
      codeId: '',
      text: '获取验证码',
      isSend: false,
    };
  },
  created() {
    let isLogin = false;
    if(this.$cookies.get('__tk')){
      isLogin = true;
      this.$router.push('/home')
    }else{
      isLogin = false;
    }
    console.log('Home isLogin==>', isLogin)
    let oj = {
      title: '落新家',
      nav: 'Register',
      isLogin: isLogin,
    };
    this.$emit('isTitle', oj);
  },

  methods: {
    goPage(n) {
      this.$router.push({ name: n });
    },

    //获取验证码
    sendCode() {
      //验证邮箱格式是否正确
      let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!reg.test(this.userInfo.email)) {
        this.$message.warning("请输入正确的邮箱！")
        return;
      }

      let time = 5;
      this.text = `${time}s后重新发送`;
      this.isSend = true;

      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          timer = null;
          this.text = '获取验证码';
          this.isSend = false;

        } else {
          time--;
          this.text = `${time}s后重新发送`;
        }
      }, 1000)

      //发起获取验证码请求
      this.axios({
        method: 'POST',
        url: this.baseUrl + '/email',
        data: {
          email: this.userInfo.email
        }
      }).then(res => {
        console.log('res ==> ', res);
        if (res.data.code == 1010) {
          this.codeId = res.data.cid;
          console.log('验证码==>', this.Code)
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => {
        this.$message.error(res.data.msg);
        console.log('err ==> ', err);
      })
    },

    // 昵称验证
    validateUserName(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入昵称"));
      } else if (!/[\u4e00-\u9fa5a-zA-Z\d]{2,10}/.test(value)) {
        callback(new Error("昵称不正确, 长度在 2 到 10 个汉字字母数字组合"));
      } else {
        callback();
      }
    },

    // 邮箱验证
    validateEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入邮箱'));
      } else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    },

    // 密码验证
    validatePass(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (!/^\w{5,10}$/.test(value)) {
          callback(new Error("请输入长度 5 到 10 位字母数字下划线组合"));
        }
        if (this.userInfo.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    },

    // 确认密码验证
    validatePass2(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.userInfo.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },

    // 手机号验证
    validatePhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      } else {
        callback();
      }
    },

    // 验证码验证
    validateCode(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (!/\d{6}/.test(value)) {
        callback(new Error("验证码错误!"));
      } else {
        callback();
      }
    },

    // 注册
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        }
        //判断是否获取验证码
        if (!this.codeId) {
          this.$message.warning('请先获取验证码');
          return;
        }

        //发起注册请求
        console.log('发起注册请求');
        this.axios({
          method: 'POST',
          url: this.baseUrl + '/register',
          data: {
            // 用户昵称
            userName: this.userInfo.userName,
            // 用户邮箱
            email: this.userInfo.email,
            // 用户密码
            password: this.userInfo.password,
            // 用户手机号
            phone: this.userInfo.phoneNumber,
            // 验证码
            validcode: this.userInfo.validcode,
            // 验证码id
            codeId: this.codeId
          }
        }).then(res => {
          console.log('res ==> ', res);
          if (res.data.code == 1000) {
            this.$message({
              message: `${res.data.msg}，准备跳转到登录页。`,
              type: 'success'
            });
            setTimeout(() => {
              this.$router.push({ name: 'Login' })
            }, 2000);
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(err => {
          console.log('err ==> ', err);
        })

      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>